import React, { Component } from 'react';
import './comment.css'

class Comment extends Component {
  constructor() {
    super()
    this.state = {
      name: '',
      content: '',
      list: []
    }
  }
  getName(e) {
    this.setState({
      name: e.target.value
    })
  }
  getContent(e) {
    this.setState({
      content: e.target.value
    })
  }
  commit() {
    // 判断是否为空
    if(this.state.name && this.state.content) {
      let arr = this.state.list;
      arr.push({
        name: this.state.name,
        content: this.state.content
      })
      this.setState({
        list: arr
      }, ()=> {
        this.setState({
          name: '',
          content: ''
        })
      })
    }
  }
  del(index) {
    let arr = this.state.list;
    arr.splice(index, 1);
    this.setState({
      list: arr
    })
  }
  render() {
    return (
      <div>
        <h1>留言板</h1>
        <input value={this.state.name} onChange={(e)=>this.getName(e)}></input>
        <br />
        <input value={this.state.content} onChange={(e)=>this.getContent(e)}></input>
        <br />
        <button onClick={()=>this.commit()}>提交留言</button>
        <hr></hr>
        {
          this.state.list.map((item, index) => {
            return (
              <div className={index%2?'red':'blue'} key={index}>
                <p>昵称：{item.name}</p>
                <p>留言：{item.content}</p>
                <button onClick={()=>this.del(index)}>del</button>
              </div>
            )
          })
        }
      </div>
    );
  }
}

export default Comment;
